package com.ls.mq.manager;

import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;

import com.ls.mq.util.Constants;

/**
 * 负责参数配置，channel配置，及启动等工作
 * 
 * @author liblc
 *
 */
public class MQService implements Runnable {
	private Logger logger = Logger.getLogger(MQService.class);
	private volatile static MQService instance;
	private Future<?> future;
	private boolean isStart = false;
	private ExecutorService executors;

	public static MQService getInstance() {
		if (instance == null)
			synchronized (MQService.class) {
				if (instance == null)
					instance = new MQService();
			}
		return instance;
	}

	private MQService() {
		isStart = false;
		executors = Executors.newSingleThreadExecutor();
	}

	public void start() {
		if(!isStart){
			future = executors.submit(this);
			try {
				Thread.sleep(1000000);//TODO 模拟长时启动,后面加到服务里面
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void stop(){
		if(isStart){
			future.cancel(true);
			MQManager.getInstance().stop();
			setStart(false);
		}
		try {
			Thread.sleep(1000);//TODO 模拟长时启动,后面加到服务里面
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void initAndStartMq() throws Exception {
		String hostName = RedisConfig.getInstance().get("hostname");
		int port = Integer.valueOf(RedisConfig.getInstance().get("port"));
		String userName = RedisConfig.getInstance().get("username");
		String password = RedisConfig.getInstance().get("password");
		MQManager.initInstance(hostName, port, userName, password);
		String localIp = InetAddress.getLocalHost().getHostAddress();
		String defaultPort = Constants.DEFAULT_PORT;
		String defaultQueueChannel = String.format("%s:%s", localIp, defaultPort);
		MQManager.getInstance().getQueueChannels().add(defaultQueueChannel);
		MQManager.getInstance().getPubsubChannels().add(Constants.DEFAULT_PUBLIC_PUBSUB_CHANNEL);
		MQManager.getInstance().start();
		setStart(true);
	}

	@Override
	public void run() {
		try {
			initAndStartMq();
		} catch (Exception e) {
			logger.error("start Mq error ",e);
		}
	}

	public boolean isStart() {
		return isStart;
	}

	public void setStart(boolean isStart) {
		this.isStart = isStart;
	}
}
